package com.example.mydianping.service.impl;

import cn.hutool.json.JSONUtil;
import com.example.mydianping.mapper.VoucherMapper;
import com.example.mydianping.mapper.VoucherSeckillMapper;
import com.example.mydianping.pojo.SeckillVoucher;
import com.example.mydianping.pojo.Voucher;
import com.example.mydianping.service.VoucherService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class VoucherServiceImpl implements VoucherService {

    @Resource
    private VoucherMapper voucherMapper;
    @Resource
    private VoucherSeckillMapper voucherSeckillMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<Voucher> queryVoucherList(long shopId) {
        return voucherMapper.selectVouchers(shopId);
    }

    @Override
    public void add(Voucher voucher) {
        //普通卷直接存到数据库即可
        voucherMapper.insert(voucher);
    }

    @Override
    public void addSecKill(Voucher voucher) {
        //先添加一个普通卷到数据库中
        add(voucher);
        //再创建普通卷对应的秒杀卷对象，并存到数据库中
        SeckillVoucher seckillVoucher = new SeckillVoucher(voucher.getId(),voucher.getStock(),voucher.getBeginTime(),voucher.getEndTime());
        voucherSeckillMapper.insert(seckillVoucher);
        //保存秒杀库存到 redis 中
        stringRedisTemplate.opsForValue().set("Voucher:seckill:"+voucher.getId(), voucher.getStock().toString());
    }
}
